import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

// 解决跳转子路由报错问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch((err) => err)
}

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/login',
    component: () => import('@/views/Login')
  },
  {
    path: '/home',
    name: 'home',
    redirect: '/welcome',
    meta: {
      auth: true
    },
    component: () => import('@/views/Home/index'),
    children: [
      {
        path: '/welcome',
        name: 'welcome',
        component: () => import('@/views/Home/Welcome/index')
      },
      {
        path: '/users',
        name: 'users',
        component: () => import('@/views/Home/Users/index')
      },
      {
        path: '/rights',
        name: 'rights',
        component: () => import('@/views/Home/Roles/rights.vue')
      },
      {
        path: '/roles',
        name: 'roles',
        component: () => import('@/views/Home/Roles/roles.vue')
      },
      {
        path: '/goods',
        name: 'goods',
        component: () => import('@/views/Home/Goods/goods.vue')
      },
      {
        path: '/addgoods',
        name: 'addgoods',
        component: () => import('@/views/Home/Goods/addgoods.vue')
      },
      {
        path: '/categories',
        name: 'categories',
        component: () => import('@/views/Home/Goods/goodsCate.vue')
      },
      {
        path: '/params',
        name: 'params',
        component: () => import('@/views/Home/Goods/goodsParams.vue')
      },
      {
        path: '/orders',
        name: 'orders',
        component: () => import('@/views/Orders/orders.vue')
      },
      {
        path: '/reports',
        name: 'reports',
        component: () => import('@/views/Reports/reports.vue')
      },
      
    ]
  }
]

const router = new VueRouter({
  routes
})

// 实现页面鉴权
router.beforeEach((to, from, next) => {
  // console.log(to)
  // 判断meta里面的auth是否为true
  const flag = to.matched.some((item) => {
    return item.meta.auth
  })
  if (!flag) {
    // 不需要鉴权 直接放行
    next()
  } else {
    // 需要鉴权还有判断有没有token
    const token = sessionStorage.getItem('token')
    // 如果没有token 跳转到登录页
    if (!token) {
      return next({
        path: '/login'
      })
    }
    next()
  }
  next()
})
export default router
